package com.huicoo.forestmanager.widget.update;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.util.LogUtils;

public class AppUpdateDialog extends Dialog {
    private TextView tv_update_title, tv_update_content;
    private TextView btn_right_now;

    private OnAppUpdateListener onAppUpdateListener;
    private String download = "";

    public AppUpdateDialog(Context context) {
        super(context, R.style.transDialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_app_update);

        tv_update_title = findViewById(R.id.tv_update_title);
        tv_update_content = findViewById(R.id.tv_update_content);
        btn_right_now = findViewById(R.id.btn_right_now);

        btn_right_now.setOnClickListener(onClickListener);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_right_now:
                    if (onAppUpdateListener != null && !TextUtils.isEmpty(download)) {
                        onAppUpdateListener.toUpdate(download);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private AppUpdateDownInfo appUpdateDownInfo;
    private boolean isForce;

    public void setUpdateInfo(AppUpdateDownInfo info, boolean isForce) {
        this.appUpdateDownInfo = info;
        this.isForce = isForce;
    }

    public void showDialog() {
        if (appUpdateDownInfo != null && !TextUtils.isEmpty(appUpdateDownInfo.downloadUrl)) {
            setCancelable(!isForce);
            setCanceledOnTouchOutside(!isForce);

            show();

            tv_update_title.setText(String.format("发现新版本！ (%s)", appUpdateDownInfo.version));
            this.download = appUpdateDownInfo.downloadUrl;
            tv_update_content.setText(appUpdateDownInfo.description);
        } else {
            LogUtils.v("gogogo info = " + (appUpdateDownInfo == null) + "  --  " + download);
            LogUtils.v("gogogo 版本更新内容设置有误");
        }
    }

    public interface OnAppUpdateListener {
        void toUpdate(String downloadUrl);
    }

    public void setOnAppUpdateListener(OnAppUpdateListener onAppUpdateListener) {
        this.onAppUpdateListener = onAppUpdateListener;
    }

}
